package com.cskaoyan.realm;

import com.cskaoyan.bean.admin.Admin;
import com.cskaoyan.mapper.AdminMapper;
import com.cskaoyan.mapper.PermissionMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class AdminRealm extends AuthorizingRealm {

    @Autowired
    AdminMapper adminMapper;
    @Autowired
    PermissionMapper permissionMapper;
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        MallToken token = (MallToken) authenticationToken;
        String username = token.getUsername();
        String credential = adminMapper.selectPasswordByUsername(username);
        Admin admin = adminMapper.selectByUsername2(username);
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(admin, credential, this.getName());
        return authenticationInfo;
    }
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Admin admin = (Admin) principalCollection.getPrimaryPrincipal();
       Integer[] roleIds =  admin.getRoleIds();
       if (roleIds == null) {
           return authorizationInfo;
       }
        List<String> permissions = new ArrayList<>();
        for (Integer roleId : roleIds) {
            List<String> partOfPermissions = permissionMapper.selectPermissions(roleId);
            permissions.addAll(partOfPermissions);
        }
        authorizationInfo.addStringPermissions(permissions);
        return authorizationInfo;
    }


}
